#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os, sys, signal
import asyncore, asynchat, socket, threading, time

HOST = "127.0.0.1"
PORT = 54344

def DEBUG(format, *args) : print format % args

will_stop = False

def signal_stop( signo, frame ) :
    global  will_stop
    DEBUG( "SERVER catch #%d signal, would stop.", signo )
    will_stop = True
    return
    # signal_stop

class echo_server(object):

    def run(self):
        global will_stop
        
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind((HOST, PORT))
        DEBUG('SERVER listening on %s:%d ...', HOST, PORT)
        sock.listen(1)
        connect, client = sock.accept()
        DEBUG('SERVER accept client %s', client)
        connect_broken = False
        while not will_stop :
            buffer = ""
            while "\n" not in buffer:
                data = connect.recv(16)
                if not data:
                    DEBUG('No data received, and connection may be broken.')
                    connect_broken = True
                    break
                buffer = buffer + data
            if connect_broken : break
            DEBUG('SERVER echo: %s', buffer)
            while buffer:
                n = connect.send(buffer)
                buffer = buffer[n:]
        if connect_broken :
            DEBUG('SERVER will close connection...')
            connect.close()
        sock.close()

def main():
    # mask signal
    signal.signal( signal.SIGTERM, signal_stop )
    if 'posix' == os.name :
        signal.signal( signal.SIGQUIT, signal_stop )

    s = echo_server()
    try :
        s.run()
    except :
        DEBUG( "SERVER interrupt : %s", `sys.exc_info()[1]` )

if __name__ == '__main__' :
    main()
    sys.exit(0)
